package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.entity.Result;
import com.itheima.service.UserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author ：daqiang
 * @date ：Created in 2019/11/16
 * @description ：
 * @version: 1.0
 */

@Controller
@RequestMapping("/user")
public class UserController {

    @Reference
    UserService userService;

    @RequestMapping("/doSuccess")
    public String doSuccess(){
        return "redirect:http://localhost:83/pages/main.html";
    }

    @RequestMapping("/doFail")
    public String doFail(){
        return "redirect:http://localhost:83/login.html?message=loginFail";
    }

    @RequestMapping("/getUsername")
    @ResponseBody
    public Result getUsername(HttpServletRequest request){
        String username = null;
        try {
            //安全框架提供一个工具类，可以直接获取session中的对象
            SecurityContext context = SecurityContextHolder.getContext();
            //认证对象
            Authentication authentication = context.getAuthentication();
            //获取principal
            Object principal = authentication.getPrincipal();
            //转换类型
            User user = (User) principal;
            //获取username
            username = user.getUsername();
            return new Result(true,MessageConst.GET_USERNAME_SUCCESS,username);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.GET_USERNAME_FAIL);
        }
    }
}
